#!/bin/sh
#
# Start/stop/restart Merecat.
#
# Copyright (C) 2023  Ricardo García Jiménez <ricardogj08@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

merecat_start() {
  if [ -r /var/run/merecat.pid ]; then
    echo "Merecat is already running: $(cat /var/run/merecat.pid)"
    exit 1
  fi

  if [ -x /usr/sbin/merecat ]; then
    /usr/sbin/merecat -f /etc/merecat.conf -I merecat -l err -P /var/run/merecat.pid -n -s /var/merecat/www & > /dev/null
    echo "Starting Merecat: /usr/sbin/merecat -f /etc/merecat.conf -I merecat -l err -P /var/run/merecat.pid -n -s /var/merecat/www & > /dev/null"
  fi
}

merecat_error() {
  echo "Merecat does not seem to be running"
  exit 1
}

merecat_stop() {
  if [ -r /var/run/merecat.pid ]; then
    kill "$(cat /var/run/merecat.pid)"
    rm -f /var/run/merecat.pid
  else
    merecat_error
  fi
}

merecat_restart() {
  merecat_stop
  merecat_start
}

merecat_status() {
  if [ -r /var/run/merecat.pid ]; then
    echo "Merecat is running: $(cat /var/run/merecat.pid)"
  else
    merecat_error
  fi
}

case "$1" in
  'start')
    merecat_start
    ;;
  'status')
    merecat_status
    ;;
  'stop')
    merecat_stop
    ;;
  'restart')
    merecat_restart
    ;;
  *)
    echo "usage $0 start|stop|restart|status"
esac
